package com.dingding.order.core.confirm.biz.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.dto.AbstractResponse;
import com.dingding.common.core.base.dto.ResponseEntity;
import com.dingding.common.core.beans.UserLogin;
import com.dingding.common.core.beans.Useraccount;
import com.dingding.common.core.beans.Userdetail;
import com.dingding.common.core.beans.Userordert;
import com.dingding.common.core.config.SystemConfig;
import com.dingding.common.core.model.push.PushModel;
import com.dingding.common.core.sms.model.MessageModel;
import com.dingding.common.core.util.DateFormatUtil;
import com.dingding.common.core.util.JSONUtil;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.common.core.util.paravalidate.ValidateUtil;
import com.dingding.facade.account.user.service.IUserAccountService;
import com.dingding.facade.queue.dto.msg.MessageRequestsDTO;
import com.dingding.facade.queue.dto.push.PushRequestDTO;
import com.dingding.facade.queue.enums.ClientType;
import com.dingding.facade.queue.enums.PushType;
import com.dingding.facade.queue.facade.IQueueFacade;
import com.dingding.facade.user.service.IUserInfoFacade;
import com.dingding.facade.user.service.IUserLoginFacade;
import com.dingding.facde.activity.dto.AttendActivityDTO;
import com.dingding.facde.activity.enums.AttendActivityEnum;
import com.dingding.facde.activity.service.IUserAttendActivityService;
import com.dingding.order.code.ConfirmArriveCodeMsg;
import com.dingding.order.core.confirm.biz.IConfirmArriveService;
import com.dingding.order.core.confirm.dao.IConfirmArriveDao;
import com.dingding.order.core.confirm.dao.IUserOrderDao;
import com.dingding.order.dto.confirm.PushAutoConfirmArrival;
import com.dingding.order.dto.confirm.PushConfirmArrival;
import com.dingding.order.dto.confirm.ReqConfirmArriveDTO;
import com.dingding.order.dto.confirm.ResConfirmArriveDTO;
import com.dingding.order.dto.publish.PushData;

@SuppressWarnings("all")
@Component("confirmArriveService")
public class ConfirmArriveServiceImpl extends AbstractResponse<ResConfirmArriveDTO,ReqConfirmArriveDTO> implements IConfirmArriveService {

	private Logger log = Logger.getLogger(this.getClass());

	// 判断是正式环境还是测试环境，如果是测试环境，则不增加取消次数
	private boolean environmentParam = SystemConfig.isEnv_system();
	
	@Autowired
	private IConfirmArriveDao confirmArriveDao; // 确认到达所用的dao

	@Autowired
	private IUserAccountService userAccountService; // 用户账户service

	@Resource(name = "userInfoService")
	private IUserInfoFacade userInfoFacade; // 用户详情facade

	@Autowired
	private IUserAttendActivityService userAttendActivityService; // 用户参加活动服务

	@Autowired
	private IQueueFacade queueFacade;
	
	@Resource(name="userLoginFacade")
	private IUserLoginFacade userLoginFacade;

	@Resource(name = "userOrderDao")
	private IUserOrderDao userOrderDao;
	
	/**
	 * @Description:确认到达
	 * @param confirmArriveReqDTO
	 * @author fengshuonan
	 * @return String
	 */
	@Override
	public String confirmArrive(String requestData) {

		ResponseEntity<ResConfirmArriveDTO> response = new ResponseEntity<ResConfirmArriveDTO>();

		ReqConfirmArriveDTO confirmArriveReqDTO = super.parseRequestJson(requestData);
		
		/**
		 * 验证请求参数是否为空
		 */
		response = (ResponseEntity<ResConfirmArriveDTO>) ValidateUtil.validateReqPara(confirmArriveReqDTO);

		if (response.getCode() != HttpStatus.SC_OK) {
			return super.responseBeanToJson(response);
		}

		/**
		 * 执行具体的业务流程
		 */
		boolean flag = concreteBiz(confirmArriveReqDTO, response);

		if (response.getCode() != HttpStatus.SC_OK) {
			return super.responseBeanToJson(response);
		}

		/**
		 * 封装返回码
		 */
		response.setCode(HttpStatus.SC_OK);

		return super.responseBeanToJson(response);
	}

	/**
	 * @Description: 确认到达具体流程
	 * @param confirmArriveReqDTO
	 * @author fengshuonan
	 * @return boolean
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	private boolean concreteBiz(ReqConfirmArriveDTO confirmArriveReqDTO, ResponseEntity<ResConfirmArriveDTO> response) {

		/**
		 * 获取到订单以及司机和乘客的账户信息
		 */
		// TODO 缓存获取订单信息

		// 获取当前确认到达订单
		Userordert carOrder = this.confirmArriveDao.getPassengerOrder(confirmArriveReqDTO.getOid());

		// 判读当前订单是否为空
		if (carOrder == null) {
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(ConfirmArriveCodeMsg.ORDER_NOT_EXISTS);
			response.setPromptMessage(ConfirmArriveCodeMsg.ORDER_NOT_EXISTS);
			return false;
		}

		// 将确认到达信息存入正式表
		boolean flag = confirmArriveDao.addToUserorderTable(carOrder);

		// 判断是否确认到达成功
		if (!flag) {
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(ConfirmArriveCodeMsg.CONFIRMARRIVE_ORDER_UPDATE_DB_ERROR);
			response.setPromptMessage(ConfirmArriveCodeMsg.CONFIRMARRIVE_ORDER_UPDATE_DB_ERROR);
			return false;
		}

		/**
		 * 进行转账操作：
		 * 
		 * 如果是合乘搭车，最后一个人确认到达时候才给司机转账，并给每个乘客返还20%的钱
		 * 
		 * 如果是一个人坐车，直接给司机转账
		 */
		// 获取所有合乘订单
		List<Userordert> sharOrderList = this.confirmArriveDao.getAllCarShareOrder(carOrder.getParOrderId());

		// 判断合乘订单中是否存在未完成订单
		if (sharOrderList != null && sharOrderList.size() > 0) {
			
			//合乘订单处理
			carpoolOrderComplete(sharOrderList, response);
			
		}
		
		// 获取司机Id
		String driverId = this.getDriverId(carOrder);
		
		// 增加接乘次数和搭乘次数
		this.addUserDetail(confirmArriveReqDTO.getPassengerId(), driverId, carOrder.getDistance(),carOrder.getUcId());
		
		// 赠送积分
//		BigDecimal integral = this.giveIntegral(driverId, carOrder.getOid());

		// 根据乘客Id或车主Id，获取发送短信和推送内容的信息
		PushConfirmArrival pushConfirmArrival = confirmArriveDao.getConfirmArrival(confirmArriveReqDTO.getPassengerId(),
				driverId);

		// 父订单Id
		pushConfirmArrival.setParentOrder(carOrder.getParOrderId());
		// 子订单Id
		pushConfirmArrival.setSubOrder(carOrder.getOid());
		// 订单状态为已完成
		pushConfirmArrival.setOrderStatus(4);
		// 积分
		pushConfirmArrival.setIntegral(new BigDecimal(0));
		// 订单类型(1:顺风车 2:出租车 3:专车4:一口价)
		pushConfirmArrival.setPublishType(1);

		// 发送短信
		sendMessage(pushConfirmArrival);
		
		// 推送消息
		pushMessage(pushConfirmArrival);

		// 用户确认到达-通知推送
		pushNotice(pushConfirmArrival);
		
		return true;
	}

	/**
	 * 
	 * @Title: updateUserDetail 
	 * @Description:  累计接乘、累计搭乘
	 * @param placeOrderUserId 下单用户(乘客)
	 * @param grabOrderUserId	抢单用户(司机)
	 * @param distance	订单里程
	 * @author YHQ 
	 * @since V2.3.0
	 * @return void    返回类型
	 * 
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public void addUserDetail(String passengerId,String driverId,BigDecimal distance,String ucId){
		
		// 获取乘客用户明细
		Userdetail passengerDetail = userInfoFacade.getUserDetail(passengerId);
		
		// 获取司机用户明细
		Userdetail driverDetail = userInfoFacade.getUserDetail(driverId);
		
		// 司机累计接乘
		driverDetail.setTotalWeldingProcess(driverDetail.getTotalWeldingProcess().add(distance));
		
		// 乘客累计搭乘
		passengerDetail.setTotalTake(passengerDetail.getTotalTake().add(distance));
		
		userInfoFacade.updateUserDetail(driverDetail);
		
		userInfoFacade.updateUserDetail(passengerDetail);
		
		// 如果乘客使用了优惠券，则修改乘客优惠券个数
		if(ToolUtil.isNotBlank(ucId)){
			userInfoFacade.updateUserCouponNumber(passengerId);
		}
	}
	
	/**
	 * 
	 * 确认到达后发送短信
	 * 
	 * @Title: sendMessage  
	 * @author CHEHAUNBO
	 * 
	 */
	public void sendMessage(PushConfirmArrival pushConfirmArrival) {

		MessageRequestsDTO messageRequestsDTO = new MessageRequestsDTO();
		messageRequestsDTO.setTelPhone(pushConfirmArrival.getTellPhone());
		messageRequestsDTO.setMessageContent(
				MessageModel.confirmArrive(pushConfirmArrival.getPassengerName(), pushConfirmArrival.getIntegral()));
		queueFacade.addMessageToQueue(JSONUtil.toJSONString(messageRequestsDTO));

	}

	/**
	 * 
	 * 确认到达后推送消息
	 * 
	 * @Title: pushMessage  
	 * @author CHEHAUNBO
	 * 
	 */
	public void pushMessage(PushConfirmArrival pushConfirmArrival) {

		// 推送Bean
		PushData pushData = new PushData();

		// 推送序号(时间戳)
		pushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
		// 推送时间
		pushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
		// 模块
		pushData.setModular("confirmArrivalPush");
		pushData.setResponseBody(pushConfirmArrival);

		PushRequestDTO pushRequestDTO = new PushRequestDTO();

		// 推送别名
		pushRequestDTO.setAliasId(pushConfirmArrival.getDriverId());
		pushRequestDTO.setAlert("订单已完成");

		// 设备类型
		if (pushConfirmArrival.getLoginEquipment().equals("Android")) {
			pushRequestDTO.setClientType(ClientType.Android);
		} else if (pushConfirmArrival.getLoginEquipment().equals("iOS")) {
			pushRequestDTO.setClientType(ClientType.iOS);
		}

		// 消息推送类型
		pushRequestDTO.setPushType(PushType.alert_msgcontent);

		// 推送类型
		pushRequestDTO.setPushContent(JSONUtil.toJSONString(pushData));

		queueFacade.addPushToQueue(JSONUtil.toJSONString(pushRequestDTO));

	}
	
	/**
	 * 
	 * 确认到达后-通知推送消息
	 * 
	 * @Title: pushNotice  
	 * @author YHQ
	 * 
	 */
	public void pushNotice(PushConfirmArrival pushConfirmArrival) {
		
		// 推送Bean
		PushData pushData = new PushData();
		
		String content = MessageModel.confirmArrive(pushConfirmArrival.getPassengerName(), pushConfirmArrival.getIntegral());
		
		// 推送序号(时间戳)
		pushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
		// 推送时间
		pushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
		// 模块
		pushData.setModular("newsNoticePush");
		// 确认到达推送内容
		pushData.setResponseBody(PushModel.noticeModel(1, content, null));
		
		PushRequestDTO pushRequestDTO = new PushRequestDTO();
		
		// 推送别名
		pushRequestDTO.setAliasId(pushConfirmArrival.getDriverId());
		
		// 设备类型
		if (pushConfirmArrival.getLoginEquipment().equals("Android")) {
			pushRequestDTO.setClientType(ClientType.Android);
		} else if (pushConfirmArrival.getLoginEquipment().equals("iOS")) {
			pushRequestDTO.setClientType(ClientType.iOS);
		}
		
		// 消息推送类型
		pushRequestDTO.setPushType(PushType.msgcontent);
		
		// 推送类型
		pushRequestDTO.setPushContent(JSONUtil.toJSONString(pushData));
		
		queueFacade.addPushToQueue(JSONUtil.toJSONString(pushRequestDTO));
		
	}

	/**
	 * @Title: getDriverId
	 * @Description: 根据订单信息和乘客Id获取司机Id
	 * @param userordert 订单信息
	 * @author yhq
	 * @return String 返回类型
	 * @throws
	 */
	public String getDriverId(Userordert userordert) {

		// 创建一个司机Id对象
		String driverId = null;

		if (userordert.getOrderType() == 1) {
			driverId = userordert.getPlaceOrderUserId();
		} else {
			driverId = userordert.getGrabOrderUserId();
		}

		return driverId;
	}

	/**
	 * @Title: getDriverId
	 * @Description: 根据订单信息和乘客Id获取司机Id
	 * @param userordert  订单信息
	 * @author yhq
	 * @return String 返回类型
	 * @throws
	 */
	public String getPassengerId(Userordert userordert) {

		// 创建一个司机Id对象
		String passengerId = null;

		if (userordert.getOrderType() == 1) {
			passengerId = userordert.getGrabOrderUserId();
		} else {
			passengerId = userordert.getPlaceOrderUserId();
		}

		return passengerId;
	}
	
	/**
	 * 
	 * @Title: confirmArrivalOperation
	 * @Description: 确认到达操作
	 * @param sharOrderList 合乘订单集合
	 * @param completeOrderNumber 合乘订单中完成订单数量
	 * @author yuHaiQing
	 * @return void    返回类型
	 * 
	 */
	public void confirmArrivalOperation(List<Userordert> sharOrderList, ResponseEntity<ResConfirmArriveDTO> response,
			int completeOrderNumber) {

		// 父订单Id
		String parentOrderId = null;
		// 时间戳
		Date lastDate = null;

		// 父订单对象
		Userordert parentOrdert = null;
		
		// 遍历合乘订单，进行相应的操作
		for (int i = 0; i < sharOrderList.size(); i++) {

			Userordert carOrder = sharOrderList.get(i);

			// 完成订单进行转账操作
			if (carOrder.getOrderStatus() == 4) {

				// 获取司机id
				String driverId = null;
				// 乘客Id
				String passengerId = null;

				if (carOrder.getOrderType() == 1) { // 司机下单
					driverId = carOrder.getPlaceOrderUserId();
					passengerId = carOrder.getGrabOrderUserId();
				} else { // 乘客下单
					driverId = carOrder.getGrabOrderUserId();
					passengerId = carOrder.getPlaceOrderUserId();
				}

				// 根据合乘订单中的完成订单，进行转账操作
				if (completeOrderNumber == 1) { // 合乘订单中只有一个完成订单
					giveDriverMoney(response, driverId, passengerId, carOrder,completeOrderNumber);
				} else if (completeOrderNumber > 1) { // 合乘订单中有两个或两个以上完成订单
					giveDriverMoneyByCarpool(response, driverId, passengerId, carOrder,completeOrderNumber);
				}

				parentOrderId = carOrder.getParOrderId();
				lastDate = carOrder.getLastDate();
			}
			
			// 获取父订单对象
			if(carOrder.getOid().equals(parentOrderId)){
				parentOrdert = carOrder;
			}
			
		}

		// 删除主订单
		if (parentOrdert != null) {

			confirmArriveDao.deleteCurrentOrder(parentOrdert);
		}
	}

	/**
	 * 
	 * @Title: giveIntegral 
	 * @Description: 赠送积分
	 * @param driverId 司机Id
	 * @author YHQ 
	 * @since V2.3.0
	 * @return void    返回类型
	 * 
	 */
	public BigDecimal giveIntegral(String driverId,String oid){
		
		AttendActivityDTO attendActivityDTO = new AttendActivityDTO();
		attendActivityDTO.setUserId(driverId); // 司机ID
		attendActivityDTO.setAttendType(AttendActivityEnum.COMPLETE_ORDER); // 参与条件
		
		// 添加积分
		BigDecimal integral = userAttendActivityService.userAttendActivity(attendActivityDTO);
		
		if (integral.compareTo(new BigDecimal(0)) != 0) {
			// 将参加活动所赠积分添加到订单表中
			userOrderDao.updateCurrentOrderReceiveIntegral(integral,oid);
		}
		
		return integral;
	}

	
	/**
	 * @Description: 给司机转账，并给乘客返还20%钱
	 * @author fengshuonan
	 * @return
	 * @return void
	 */
	public ResponseEntity<ResConfirmArriveDTO> giveDriverMoneyByCarpool(ResponseEntity<ResConfirmArriveDTO> response,
			String driverId, String passengerId, Userordert order,int completeOrderNumber) {

		log.info("---- 合乘订单完成，给司机转账乘客返现 ----");

		// 获取司机用户账户信息
		Useraccount driverAccount = this.userAccountService.getUserAccount(driverId);

		if (driverAccount == null) {
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage("车主id不正确!");
			return response;
		}

		// 司机实收金额
		BigDecimal driverMoney = order.getTotalMoney().multiply(new BigDecimal(0.8)).setScale(1, BigDecimal.ROUND_UP);
		// 乘客返现金额
//		BigDecimal passengerMoney = new BigDecimal(0.2).multiply((order.getTotalMoney().subtract(order.getCouponMoney()).subtract(new BigDecimal(2))));//减去优惠金额，减去平台费
		BigDecimal passengerMoney = order.getTotalMoney().subtract(driverMoney);//减去优惠金额，减去平台费

		log.info("里程费用： " + order.getTotalMoney() + "  优惠金额： " + order.getCouponMoney());

		log.info("司机收钱: " + driverMoney + "  ---------------  乘客返现: " + passengerMoney);

		// 给车主转账
		driverAccount.setCurrencyAmount(driverAccount.getCurrencyAmount().add(driverMoney));

		// 给乘客返钱
		Useraccount passengerAccount = this.userAccountService.getUserAccount(passengerId);
		BigDecimal currentMoney = passengerAccount.getCurrencyAmount() == null ? new BigDecimal(0.0) : passengerAccount.getCurrencyAmount();
		passengerAccount.setCurrencyAmount(currentMoney.add(passengerMoney));

		// 添加累计信息
		addLeijiStat(driverAccount, passengerAccount, order,completeOrderNumber);

		// 移除当前订单
		boolean flag = confirmArriveDao.deleteCurrentOrder(order);

		if (!flag) {
			log.error("合乘订单 - 移除当前订单失败");
		}

		return response;
	}

	/**
	 * @Description: 给司机转账
	 * @author fengshuonan
	 * @return ResponseEntity<ConfirmArriveResDTO>
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	private ResponseEntity<ResConfirmArriveDTO> giveDriverMoney(ResponseEntity<ResConfirmArriveDTO> response,
			String driverId, String passengerId, Userordert order,int completeOrderNumber) {

		Useraccount driverAccount = this.userAccountService.getUserAccount(driverId);
		Useraccount passengerAccount = this.userAccountService.getUserAccount(passengerId);

		if (driverAccount == null || passengerAccount == null) {
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage("车主id或乘客id不正确!");
			return response;
		}

		driverAccount.setCurrencyAmount(driverAccount.getCurrencyAmount().add(order.getTotalMoney()));

		// 添加累计信息
		addLeijiStat(driverAccount, passengerAccount, order,completeOrderNumber);

		// 移除当前订单
		boolean flag = confirmArriveDao.deleteCurrentOrder(order);

		if (!flag) {
			log.error("非合乘订单 - 移除当前订单失败");
		}

		return response;
	}

	/**
	 * @Description: 增加累计数据
	 * @param driver
	 *            车主账户
	 * @param passenger
	 *            乘客账户
	 * @author fengshuonan
	 * @return void
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	private void addLeijiStat(Useraccount driver, Useraccount passenger, Userordert order,int completeOrderNumber) {

		if(environmentParam){
			//订单确认到达，给双方增加完成订单次数
			userLoginFacade.addConfirmArrival(driver.getLoginId(), passenger.getLoginId(),order.getUcId());
		}
		
		// 获取车主的详细信息
		Userdetail driverDetail = this.userInfoFacade.getUserDetail(driver.getLoginId());
		
		// 获取乘客的详细信息
		Userdetail passengerDetail = this.userInfoFacade.getUserDetail(passenger.getLoginId());
		
		passenger.setTotalExpend(passenger.getTotalExpend().add(order.getTotalMoney()).subtract(order.getCouponMoney()).add(new BigDecimal(2)));// 乘车搭车累计支出
		passengerDetail.setTotalTake(passengerDetail.getTotalTake().add(order.getDistance()));// 乘客累计搭乘
		passengerDetail.setTotalTakeNumber(passengerDetail.getTotalTakeNumber() + 1); // 乘客总搭乘次数+1
		driver.setTotalIncome(driver.getTotalIncome().add(order.getTotalMoney()));// 司机搭人累计收入
		driverDetail.setTotalWeldingProcess(driverDetail.getTotalWeldingProcess().add(order.getDistance()));// 司机累计接乘
		driverDetail.setTotalWeldingProcessNumber(driverDetail.getTotalWeldingProcessNumber() + 1);// 司机总接乘次数+1
		
		// 修改用户账户信息
		this.userAccountService.updateAccount(driver);
		this.userAccountService.updateAccount(passenger);

		// 增加交易记录详情
		this.userAccountService.addAccountDetail(passenger.getLoginId(),order.getTotalMoney().add(new BigDecimal(2)),order.getTotalMoney().subtract(order.getCouponMoney()).add(new BigDecimal(2)),order.getCouponMoney(), 2);
		
		if(completeOrderNumber == 1){ //订单中有一个完成了订单（非合乘单，不返现）
			this .userAccountService.addAccountDetail(driver.getLoginId(), order.getTotalMoney(),order.getTotalMoney().subtract(order.getCouponMoney()),order.getCouponMoney(), 1);
		}else{
			this .userAccountService.addAccountDetail(driver.getLoginId(), order.getTotalMoney().multiply(new BigDecimal(0.8)),new BigDecimal(0),new BigDecimal(0), 1);
			this .userAccountService.addAccountDetail(passenger.getLoginId(), new BigDecimal(0.2).multiply((order.getTotalMoney().subtract(order.getCouponMoney()))),new BigDecimal(0),new BigDecimal(0), 5);
		}
	}

	/**
	 * 
	 * @Title: automaticConfirmArrive 
	 * @Description: 自动确认到达 
	 * @author YHQ 
	 * @return void    返回类型
	 * 
	 */
	@Override
	public void automaticConfirmArrive() {

		//响应Bean
		ResponseEntity<ResConfirmArriveDTO> response = new ResponseEntity<ResConfirmArriveDTO>();
		
		// 获取自动确认到达订单
		List<Userordert> userorderts = confirmArriveDao.getUserOrdertByOverTime();

		// 将自动确认到达订单完成确认到达
		if(userorderts != null && userorderts.size() > 0){
			
			for (Userordert carOrder : userorderts) {
				
				carOrder.setEndTime(new Date());//确认到达时间
				carOrder.setOrderStatus(4);//确认到达
				
				// 将确认到达信息存入正式表
				boolean flag = confirmArriveDao.addToUserorderTable(carOrder);
				
				//修改临时信息
				confirmArriveDao.updateOrderInfo(carOrder);
				
				/**
				 * 进行转账操作：
				 * 
				 * 如果是合乘搭车，最后一个人确认到达时候才给司机转账，并给每个乘客返还20%的钱
				 * 
				 * 如果是一个人坐车，直接给司机转账
				 */
				// 获取所有合乘订单
				List<Userordert> sharOrderList = this.confirmArriveDao.getAllCarShareOrder(carOrder.getParOrderId());
				
				// 判断合乘订单中是否存在未完成订单
				if (sharOrderList != null && sharOrderList.size() > 0) {
					//合乘订单完成操作
					carpoolOrderComplete(sharOrderList, response);
				}
				
				// 获取司机Id
				String driverId = this.getDriverId(carOrder);
				//获取乘客Id
				String passengerId = this.getPassengerId(carOrder);

				// 增加接乘次数和搭乘次数
				this.addUserDetail(passengerId, driverId, carOrder.getDistance(),carOrder.getUcId());
				
				// 赠送积分
//				BigDecimal integral = this.giveIntegral(driverId, carOrder.getOid());
				
				// 根据乘客Id或车主Id，获取发送短信和推送内容的信息
				PushAutoConfirmArrival pushConfirmArrival = confirmArriveDao.getConfirmOrders(passengerId, driverId);

				// 父订单Id
				pushConfirmArrival.setParentOrder(carOrder.getParOrderId());
				// 子订单Id
				pushConfirmArrival.setSubOrder(carOrder.getOid());
				// 订单状态为已完成
				pushConfirmArrival.setOrderStatus(4);
				// 积分
				pushConfirmArrival.setIntegral(new BigDecimal(0));
				//发布订单类型
				pushConfirmArrival.setPublishType(1);

				// 推送短信
				sendMessageByAutoConfirmArrival(pushConfirmArrival);
				// 推送消息
				pushMessageByAutoConfirmArrival(pushConfirmArrival);
				// 通知消息
				pushNoticeMessageByAutoConfirmArrival(pushConfirmArrival);
			}
			
		}

	}

	/**
	 * 
	 * @Title: sendMessageByAutoConfirmArrival
	 * @Description: 自动确认到达发送短信
	 * @param pushConfirmArrival 通知Bean
	 * @author yuHaiQing
	 * @return void    返回类型
	 * 
	 */
	public void sendMessageByAutoConfirmArrival(PushAutoConfirmArrival pushConfirmArrival){
		
		if(ToolUtil.isNotBlank(pushConfirmArrival.getDriverPhone())){
			
			//司机发送短信内容
			MessageRequestsDTO driverDTO = new MessageRequestsDTO();
			
			driverDTO.setTelPhone(pushConfirmArrival.getDriverPhone()); //司机手机号
			driverDTO.setMessageContent(MessageModel.confirmArrive(pushConfirmArrival.getPassengerName(), pushConfirmArrival.getIntegral())); //司机发送短信内容 
			
			//给司机发送短信内容加入队列
			queueFacade.addMessageToQueue(JSONUtil.toJSONString(driverDTO));
		}
		
		if(ToolUtil.isNotBlank(pushConfirmArrival.getPassengerPhone())){
			
			//乘客发送短信内容
			MessageRequestsDTO passengerDTO = new MessageRequestsDTO();
			
			passengerDTO.setTelPhone(pushConfirmArrival.getPassengerPhone()); //乘客手机号
			passengerDTO.setMessageContent(MessageModel.AUTO_CONFIRM_ARRIVAL); //乘客发送短信内容
			
			//给乘客发送短信内容加入队列
			queueFacade.addMessageToQueue(JSONUtil.toJSONString(passengerDTO));
		}
		
	}
	
	/**
	 * 
	 * @Title: pushMessageByAutoConfirmArrival
	 * @Description: 自动确认到达推送消息
	 * @param  pushConfirmArrival 通知Bean
	 * @author yuHaiQing
	 * @return void    返回类型
	 * 
	 */
	public void pushMessageByAutoConfirmArrival(PushAutoConfirmArrival pushConfirmArrival){
		
		/*----------------给司机推送-----------------*/
		
		if(ToolUtil.isNotBlank(pushConfirmArrival.getDriverAliasId())){
			
			//给司机推送消息内容
			PushRequestDTO driverDTO = new PushRequestDTO();
			
			// 推送Bean
			PushData driverPushData = new PushData();
			
			// 推送序号(时间戳)
			driverPushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
			// 推送时间
			driverPushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
			// 模块
			driverPushData.setModular("confirmArrivalPush");
			driverPushData.setResponseBody(pushConfirmArrival);
			
			// 推送别名
			driverDTO.setAliasId(pushConfirmArrival.getDriverAliasId());
			driverDTO.setAlert("订单已完成");
			
			// 设备类型
			if (pushConfirmArrival.getDriverEquipment().equals("Android")) {
				driverDTO.setClientType(ClientType.Android);
			} else if (pushConfirmArrival.getDriverEquipment().equals("iOS")) {
				driverDTO.setClientType(ClientType.iOS);
			}
			
			// 消息推送类型
			driverDTO.setPushType(PushType.alert_msgcontent);
			
			// 推送类型
			driverDTO.setPushContent(JSONUtil.toJSONString(driverPushData));
			
			//给司机推送
			queueFacade.addPushToQueue(JSONUtil.toJSONString(driverDTO));
			
		}
		
		/*-----------------------------------------给乘客推送-----------------------------------------------*/
		
		if(ToolUtil.isNotBlank(pushConfirmArrival.getPassengerAliasId())){
			
			//给司机推送消息内容
			PushRequestDTO passengerDTO = new PushRequestDTO();
			
			// 推送Bean
			PushData passengerPushData = new PushData();
			
			// 推送序号(时间戳)
			passengerPushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
			// 推送时间
			passengerPushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
			// 模块
			passengerPushData.setModular("confirmArrivalPush");
			passengerPushData.setResponseBody(pushConfirmArrival);
			
			// 推送别名
			passengerDTO.setAliasId(pushConfirmArrival.getPassengerAliasId());
			passengerDTO.setAlert("订单已完成");
			
			// 设备类型
			if (pushConfirmArrival.getPassengerEquipment().equals("Android")) {
				passengerDTO.setClientType(ClientType.Android);
			} else if (pushConfirmArrival.getPassengerEquipment().equals("iOS")) {
				passengerDTO.setClientType(ClientType.iOS);
			}
			
			// 消息推送类型
			passengerDTO.setPushType(PushType.alert_msgcontent);
			
			// 推送类型
			passengerDTO.setPushContent(JSONUtil.toJSONString(passengerPushData));
			
			//给乘客推送
			queueFacade.addPushToQueue(JSONUtil.toJSONString(passengerDTO));
			
		}
	}
	
	/**
	 * 
	 * @Title: pushNoticeMessageByAutoConfirmArrival
	 * @Description: 自动确认到达  - 推送通知消息
	 * @param  pushConfirmArrival 通知Bean
	 * @author yuHaiQing
	 * @return void    返回类型
	 * 
	 */
	public void pushNoticeMessageByAutoConfirmArrival(PushAutoConfirmArrival pushConfirmArrival){
		
		/*----------------给司机推送-----------------*/
		
		if(ToolUtil.isNotBlank(pushConfirmArrival.getDriverAliasId())){
			
			//给司机推送消息内容
			PushRequestDTO driverDTO = new PushRequestDTO();
			
			// 推送Bean
			PushData driverPushData = new PushData();
			
			String driverContent = MessageModel.confirmArrive(pushConfirmArrival.getPassengerName(), pushConfirmArrival.getIntegral());
			
			// 推送序号(时间戳)
			driverPushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
			// 推送时间
			driverPushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
			// 模块
			driverPushData.setModular("confirmArrivalPush");
			// 推送内容
			driverPushData.setResponseBody(PushModel.noticeModel(1, driverContent, null));
			
			// 推送别名
			driverDTO.setAliasId(pushConfirmArrival.getDriverAliasId());
			driverDTO.setAlert("订单已完成");
			
			// 设备类型
			if (pushConfirmArrival.getDriverEquipment().equals("Android")) {
				driverDTO.setClientType(ClientType.Android);
			} else if (pushConfirmArrival.getDriverEquipment().equals("iOS")) {
				driverDTO.setClientType(ClientType.iOS);
			}
			
			// 消息推送类型
			driverDTO.setPushType(PushType.msgcontent);
			
			// 推送类型
			driverDTO.setPushContent(JSONUtil.toJSONString(driverPushData));
			
			//给司机推送
			queueFacade.addPushToQueue(JSONUtil.toJSONString(driverDTO));
			
		}
		
		/*-----------------------------------------给乘客推送-----------------------------------------------*/
		
		if(ToolUtil.isNotBlank(pushConfirmArrival.getPassengerAliasId())){
			
			//给司机推送消息内容
			PushRequestDTO passengerDTO = new PushRequestDTO();
			
			// 推送Bean
			PushData passengerPushData = new PushData();
			
			String passengerContent = MessageModel.AUTO_CONFIRM_ARRIVAL;
			
			// 推送序号(时间戳)
			passengerPushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
			// 推送时间
			passengerPushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
			// 模块
			passengerPushData.setModular("confirmArrivalPush");
			// 推送内容
			passengerPushData.setResponseBody(PushModel.noticeModel(1, passengerContent, null));
			
			// 推送别名
			passengerDTO.setAliasId(pushConfirmArrival.getPassengerAliasId());
			
			// 设备类型
			if (pushConfirmArrival.getPassengerEquipment().equals("Android")) {
				passengerDTO.setClientType(ClientType.Android);
			} else if (pushConfirmArrival.getPassengerEquipment().equals("iOS")) {
				passengerDTO.setClientType(ClientType.iOS);
			}
			
			// 消息推送类型
			passengerDTO.setPushType(PushType.msgcontent);
			
			// 推送类型
			passengerDTO.setPushContent(JSONUtil.toJSONString(passengerPushData));
			
			//给乘客推送
			queueFacade.addPushToQueue(JSONUtil.toJSONString(passengerDTO));
			
		}
	}
	
	/**
	 * 
	 * @Title: carpoolOrderComplete
	 * @Description: 合乘订单完成操作
	 * @param carOrder 
	 * @param response
	 * @author yuHaiQing
	 * @return void    返回类型
	 * 
	 */
	public void carpoolOrderComplete(List<Userordert> sharOrderList,ResponseEntity<ResConfirmArriveDTO> response){
		
		boolean isCompleteOrder = false; // 是否存在未完成订单 true:存在未完成订单
		// false:不存在未完成订单
		int completeOrderNumber = 0; // 完成订单数量
		
		for (Userordert userordert : sharOrderList) {
		
			// 是否存在未完成订单
			if (userordert.getIsChildren() == 2 && userordert.getOrderStatus() < 4) {
				isCompleteOrder = true;
				break;
			}
			
			// 完成订单个数
			if (userordert.getOrderStatus() == 4) {
				completeOrderNumber += 1;
			}
			
		}
		
		// 合乘订单最后一个订单确认到达
		if (!isCompleteOrder) {
			confirmArrivalOperation(sharOrderList, response, completeOrderNumber);
		}
			
	}
	
}
